import { Injectable, signal } from '@angular/core';

export interface UndoRedoState {
  canUndo: boolean;
  canRedo: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class UndoRedoService {
  private _history: any[] = [];
  private _currentIndex = signal(-1);
  private _state = signal<UndoRedoState>({ canUndo: false, canRedo: false });

  readonly state = this._state.asReadonly();

  pushState(state: any) {
    this._history = this._history.slice(0, this._currentIndex() + 1);
    this._history.push(state);
    this._currentIndex.set(this._history.length - 1);
    this.updateState();
  }

  undo(): any | null {
    if (this._currentIndex() > 0) {
      this._currentIndex.update(index => index - 1);
      this.updateState();
      return this._history[this._currentIndex()];
    }
    return null;
  }

  redo(): any | null {
    if (this._currentIndex() < this._history.length - 1) {
      this._currentIndex.update(index => index + 1);
      this.updateState();
      return this._history[this._currentIndex()];
    }
    return null;
  }

  private updateState() {
    this._state.set({
      canUndo: this._currentIndex() > 0,
      canRedo: this._currentIndex() < this._history.length - 1
    });
  }
}
